<template>
    <div class="Search">
        <div class="Search-box">
            <form action="/">
                <van-search overlay="true" ref="input" @input="changeInput" v-model="value" show-action clearable placeholder="唐诗里的烟火人间" shape="round" @search="onSearch" @cancel="onCancel" />
            </form>
        </div>
        <van-popup v-model="show" duration="0" position="top" :style="{ height: 'auto' }">
            <div class="item itemf" @click="onSearch(value)">
                <van-icon name="search" class="icon" size="20px" />
                <div class="text" v-html="this.searchTips"></div>
            </div>
            <div class="item" v-for="(item, index) in searchSuggest" :key="index" @click="goBookDetails(item.id, item.text)">
                <div class="text" v-html="item.heightText"></div>
                <van-icon name="arrow" class="arrow" />
            </div>
        </van-popup>
        <div class="content-box" v-show="value == ''">
            <!-- 热门搜索 -->
            <div class="Hot">
                <div class="Hot-title">热门搜索</div>
                <div class="Hot-box clearfix" v-if="HotSearchData !== null">
                    <div class="Hot-item" v-for="(item, index) in HotSearchData" @click="onSearch(item.name)">
                        <!-- 排名123 -->
                        <div>
                            <p :style="activation(index + 1)">{{ index + 1 }}</p>
                        </div>
                        <div class="Hot-item-name">{{ item.name }}</div>
                    </div>
                </div>
            </div>
            <!-- 最近搜索 -->
            <div class="Recently">
                <div class="title-remove">
                    <div class="Recently-title">最近搜索</div>
                    <van-icon name="delete-o" @click="remove" />
                </div>
                <div class="Recently-box clearfix" v-if="NewRecentlyData !== null">
                    <div class="Recently-item" v-for="(item, index) in NewRecentlyData" @click="onSearch(item)">
                        <van-icon name="search" />
                        {{ item }}
                    </div>
                </div>
            </div>
            <!-- 当搜索结果为空时 -->
            <div class="SearchResultnull" v-if="SearchData !== null && SearchData.length == 0">暂无数据哦~</div>
        </div>
        <!-- 搜索结果 -->
        <div class="searchResult" v-show="value !== ''">
            <!-- 结果操作栏 -->
            <div class="operation-box">
                <van-dropdown-menu>
                    <van-dropdown-item v-model="value1" :options="option1" @change="change" />
                    <van-dropdown-item v-model="value2" :options="option2" @change="change" />
                    <van-dropdown-item title="筛选" ref="item" @click="onConfirm"></van-dropdown-item>
                </van-dropdown-menu>
            </div>
            <div class="title">书城</div>
            <!-- 结果 -->
            <div class="item-box">
                <div class="item" v-for="(item, index) in SearchData" :key="item.articleUuid" @click="goBookDetails(item.sourceUuid, item.title)">
                    <div class="img-box">
                        <img class="img-auto" :src="item.coverImage" v-if="item.coverImage" :onerror="defaultImg" />
                    </div>
                    <div class="RigMsg">
                        <div class="name">{{ item.title }}</div>
                        <div class="author-type">{{ item.author }} / {{ item.category }}</div>
                        <div class="desc" v-if="item.description" v-html="item.description"></div>
                        <div class="desc" v-if="item.summary" v-html="item.summary"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { Toast } from "vant";

export default {
    name: "Search",
    data() {
        return {
            value: "",
            // 热门搜索数据
            HotSearchData: null,
            // 最近搜索数据
            RecentlyData: [],
            NewRecentlyData: null,
            // 回车搜索数据
            SearchData: null,
            // 是否展示弹出层
            show: false,
            // 搜索建议
            searchSuggest: null,
            // 搜索提示
            searchTips: null,
            sort: 0,
            channel: 0,
            // 触底次数
            count: 0,
            defaultImg: 'this.src="' + require("../assets/images/defaultImg.png") + '"',
            // 搜索结果操作栏
            value1: 0,
            value2: "a",
            option1: [
                { text: "综合排序", value: 0 },
                { text: "销量最高", value: 1 },
                { text: "人气最旺", value: 2 },
                { text: "最新上架", value: 3 },
                { text: "最近更新", value: 4 },
            ],
            option2: [
                { text: "全部频道", value: "a" },
                { text: "男生", value: "b" },
                { text: "女生", value: "c" },
                { text: "出版", value: "d" },
            ],
            option3: [
                { text: "全部频道", value: "a" },
                { text: "男生", value: "b" },
                { text: "女生", value: "c" },
                { text: "出版", value: "d" },
            ],
        };
    },
    created() {
        this.HotSearch();
        // 获取本地最近搜索数据
        setTimeout(() => {}, 100);
        // 进入页面获取输入框焦点
        this.$nextTick(() => {
            this.$refs.input.childNodes[0].childNodes[0].childNodes[1].childNodes[0].childNodes[0].focus();
        });
        // this.onSearch();
        this.NewRecentlyData = JSON.parse(localStorage.getItem("RecentlyData"));
    },
    mounted() {
        this.inputDom = this.$refs.input;
        this.inputDom;
        // 监听页面滚动
        window.addEventListener("scroll", this.getbottom);
    },
    destroyed() {
        // 清除监听
        window.removeEventListener("scroll", this.getbottom);
    },
    computed: {
        activation() {
            return (index) => {
                if (index === 1) {
                    return { background: "#e74c2c" };
                } else if (index === 2) {
                    return { background: "#fe7817" };
                } else if (index === 3) {
                    return { background: "#ffbf01" };
                } else {
                    return { background: "#d9d9d9" };
                }
            };
        },
    },
    methods: {
        // 封装一个根据书籍排序方式以及频道不同搜索不同结果的函数
        differentType(sort, channel) {
            this.axios({
                method: "get",
                url: "search/book.json",
                params: {
                    keyword: this.value,
                    page: "1",
                    sort,
                    channel,
                },
            })
                .then((res) => {
                    this.SearchData = res.data.data.books;
                    //
                })
                .catch((err) => {
                    err;
                });
        },
        // 操作栏改变时
        change() {
            //
            //
            // 排序
            if (this.value1 == 0) {
                this.sort = 0;
            } else if (this.value1 == 1 || this.value1 == 2) {
                // 1与2好像结果一样
                this.sort = 1;
            } else if (this.value1 == 3) {
                this.sort = 3;
            } else {
                this.sort = 4;
            }

            // 频道
            if (this.value2 == "a") {
                this.channel = 0;
            } else if (this.value2 == "b") {
                this.channel = 1;
            } else if (this.value2 == "c") {
                this.channel = 2;
            } else {
                this.channel = 3;
            }

            // 结合两个参数筛选书籍
            this.differentType(this.sort, this.channel);
        },

        getbottom() {
            // 返回滚动条垂直滚动距离
            let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            // 返回该元素的像素高度，高度包含内边距（padding），不包含边框（border），外边距（margin）和滚动条
            let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
            // 返回该元素的像素高度，高度包含内边距（padding），不包含外边距（margin）、边框（border）
            let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
            let numHeight = scrollTop + clientHeight;
            if (scrollHeight > clientHeight && numHeight > scrollHeight - 1) {
                this.count++;
                // 触底获取第count+1页的书籍
                this.touchGround(this.sort, this.channel, this.count + 1);
            }
        },

        // 触底加载第count+1页的书籍函数
        touchGround(sort, channel, page) {
            this.axios({
                method: "get",
                url: "search/book.json",
                params: {
                    keyword: this.value,
                    sort,
                    channel,
                    page,
                },
            })
                .then((res) => {
                    let countPage = res.data.data.books;
                    this.SearchData.push(...countPage);
                })
                .catch((err) => {
                    err;
                });
        },

        // 打开收起筛选
        onConfirm() {
            this.$refs.item.toggle();
        },
        // 删除最近搜索
        remove() {
            if (JSON.parse(localStorage.getItem("RecentlyData"))) {
                localStorage.removeItem("RecentlyData");
                this.NewRecentlyData = JSON.parse(localStorage.getItem("RecentlyData")) || [];
                this.RecentlyData = [];
                Toast.success("删除成功");
            } else {
                Toast.fail("没有搜索记录");
            }
        },
        changeInput() {
            if (this.value.trim() !== "") {
                this.show = true;
                // 根据关键词获取搜索建议
                this.axios({
                    methods: "get",
                    url: "yunyuedu/search/searchHint?search=" + this.value,
                })
                    .then((res) => {
                        //
                        // 保存搜索建议结果
                        if (res.data.words !== "") {
                            this.searchSuggest = res.data.words.w;
                            for (let i = 0; i < this.searchSuggest.length; i++) {
                                this.searchSuggest[i].heightText = this.highlight(this.searchSuggest[i].text, this.value);
                            }
                        }
                    })
                    .catch((err) => {});
            } else {
                this.show = false;
            }

            // 搜索提示高亮
            this.searchTips = "搜索" + this.value;
            let arr = this.searchTips.split(this.value);
            this.searchTips = arr.join(`<span style="color: #FF4d00">${this.value}</span>`);
            //
        },
        // 搜索建议关键词高亮
        highlight(source, keyword) {
            const reg = new RegExp(keyword, "gi");
            //

            return source.replace(reg, `<span style="color: #FF4d00">${keyword}</span>`);
        },
        // 回车
        onSearch(val) {
            this.show = false;
            // 点击可请求
            this.value = val;
            // 防止重复
            if (this.value.trim() !== "") {
                let RecentlyData = JSON.parse(localStorage.getItem("RecentlyData")) || [];

                if (RecentlyData.length > 0 && RecentlyData.indexOf(this.value) == -1) {
                    RecentlyData.push(this.value);
                } else if (RecentlyData.length == 0) {
                    RecentlyData.push(this.value);
                    // localStorage.setItem("RecentlyData", JSON.stringify(RecentlyData));
                }

                localStorage.setItem("RecentlyData", JSON.stringify(RecentlyData));
                if (JSON.parse(localStorage.getItem("RecentlyData"))) {
                    this.NewRecentlyData = JSON.parse(localStorage.getItem("RecentlyData"));
                }
                // 搜索
                this.axios({
                    method: "get",
                    url: "search/book/data.json",
                    params: {
                        key: this.value,
                        page: "1",
                    },
                })
                    .then((res) => {
                        this.SearchData = res.data.data.books;
                        //
                    })
                    .catch((err) => {
                        err;
                    });
            }

            // 清空输入框的内容
            // this.value = "";
        },
        // 点击取消按钮
        onCancel() {
            this.$router.back();
        },
        // 热门搜索
        HotSearch() {
            this.axios({
                method: "get",
                url: "search/getHotWords",
            })
                .then((res) => {
                    res;
                    this.HotSearchData = res.data.list;
                })
                .catch((err) => {
                    err;
                });
        },
        // 跳转书籍详情
        goBookDetails(BookId, title) {
            this.$router.push({
                name: "BookDetails",
                query: {
                    BookId,
                    title,
                },
            });
        },
    },
    watch: {
        // 监听搜索框,回车后获取焦点
        value(newval, oldval) {
            if (newval == "") {
                this.$nextTick(() => {
                    this.$refs.input.childNodes[0].childNodes[0].childNodes[1].childNodes[0].childNodes[0].focus();
                });
            }
        },
    },
};
</script>

<style lang="less" scoped>
.Search {
    &::-webkit-scrollbar {
        display: none;
    }
    ::v-deep {
        .van-overlay {
            top: 50px;
            background-color: #fff;
        }
    }

    .van-popup--top {
        top: 50px;
        .item {
            height: 50px;
            border-bottom: 1px dashed #686969;
            padding: 0 20px;
            line-height: 50px;

            position: relative;
            .text {
                width: 80%;
                font-size: 14px;
                display: -webkit-box;
                -webkit-box-orient: vertical;
                -webkit-line-clamp: 1;
                overflow: hidden;
            }
            .arrow {
                position: absolute;
                top: 50%;
                right: 10px;
                transform: translateY(-50%);
                color: #686969;
            }
        }

        .itemf {
            display: flex;
            align-items: center;

            .icon {
                margin-right: 10px;
            }
        }
    }
    .Search-box {
        height: 50px;

        &::-webkit-scrollbar {
            display: none;
        }
        ::v-deep {
            .van-search__action {
                color: #9b9f9f;
            }
        }
    }
    .searchResult {
        // position: fixed;
        // top: 50px;
        // left: 0;
        // bottom: 0;
        // right: 0;
        // overflow-y: scroll;
        height: calc(100% - 100px);
        .operation-box {
            height: 48px;
        }
        .title {
            height: 35px;
            background-color: #d4dddd;
            padding-left: 20px;
            line-height: 35px;
            font-size: 16px;
        }
        .item-box {
            padding: 10px 20px;
            .item {
                height: 100px;
                // background-color: red;
                margin-bottom: 10px;
                display: flex;
                align-items: center;

                .img-box {
                    width: 20%;
                    height: 94px;
                    box-shadow: 0 0 6px #686969;
                    img {
                        overflow: hidden;
                    }
                }
                .RigMsg {
                    height: 100%;
                    width: calc(80% - 15px);
                    margin-left: 10px;
                    .name {
                        height: 20px;
                        font-size: 16px;
                        font-weight: 700;
                        margin-bottom: 5px;
                        display: -webkit-box;
                        -webkit-box-orient: vertical;
                        -webkit-line-clamp: 1;
                        overflow: hidden;
                    }
                    .author-type {
                        color: #686969;
                        margin-bottom: 10px;
                        height: 30px;
                        display: -webkit-box;
                        -webkit-box-orient: vertical;
                        -webkit-line-clamp: 2;
                        overflow: hidden;
                    }
                    .desc {
                        height: 30px;
                        // width: 265px;
                        // 给容器元素类型转换为
                        display: -webkit-box;
                        // 设置弹性盒子垂直排列
                        -webkit-box-orient: vertical;
                        // 控制要显示的行数
                        -webkit-line-clamp: 2;
                        // 溢出隐藏
                        overflow: hidden;
                        text-align-last: left;
                        color: #686969;
                    }
                }
            }
        }
    }
    .content-box {
        height: calc(100% - 50px);

        .Hot,
        .Recently {
            width: 350px;
            margin: 30px auto;
            .Hot-box,
            .Recently-box {
                margin: 10px 0 0 0;

                .Hot-item {
                    width: 50%;
                    float: left;
                    margin: 10px 0 0 0;
                    font-weight: 550;
                    display: flex;
                    align-items: center;
                    .Hot-item-name {
                        min-width: 140px;
                        display: -webkit-box;
                        -webkit-box-orient: vertical;
                        -webkit-line-clamp: 1;
                        overflow: hidden;
                        font-weight: bolder;
                        font-size: 16px;
                    }
                    div {
                        margin-top: 10px;
                        margin-right: 10px;
                        line-height: 20px;
                        width: 20px;
                        height: 20px;

                        p {
                            width: 20px;
                            height: 20px;
                            color: white;
                            background: #e64c2c;
                            border-radius: 50%;
                            margin: 0 0 0 0;
                            text-align: center;
                        }
                    }
                }
            }

            .Hot-title,
            .Recently-title {
                color: #9b9f9f;
            }
        }
        .Recently {
            .Recently-box {
                display: flex;
                align-items: center;
                flex-wrap: wrap;
                .Recently-item {
                    margin: 0 10px 10px 0;
                    display: flex;
                    align-items: center;
                    border: 1px solid #686969;
                    border-radius: 20px;
                    background-color: #eceded;
                    padding: 5px 10px;
                    font-size: 14px;
                    .van-icon-search {
                        font-size: 14px;
                    }
                }
            }
            .title-remove {
                display: flex;
                align-items: center;
                justify-content: space-between;
                .van-icon-delete-o {
                    font-size: 16px;
                    color: #9b9f9f;
                }
            }
        }
    }
}
</style>
